﻿using ERPSystem.Common.Domains.CustomerProfileCommon;
using ERPSystem.Common.Domains.SalesOrderCommom;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;
using Microsoft.Extensions.FileSystemGlobbing.Internal;
using NPOI.SS.Formula.Functions;
using SalesManagementCommon.API.SalesManagementCommons.SalesManagementSerach;
using SqlSugar;
using System.Reflection.Metadata;
using System.Xml.Linq;

namespace SalesManagementCommon.API.SalesManagementCommons.SalesOrderSearch
{
    public class SalesOrderSearchHander : IRequestHandler<SalesOrderSearchCommand, Result<PageResultDto<SalesOrderSearchDTO>>>
    {

        private readonly ISqlSugarClient _db;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="_db"></param>
        public SalesOrderSearchHander(ISqlSugarClient _db)
        {
            this._db = _db;
        }

        /// <summary>
        /// 处理销售订单详细信息查询命令
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result<PageResultDto<SalesOrderSearchDTO>>> Handle(SalesOrderSearchCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<SalesOrderSearchDTO>>();
            var page = new PageResultDto<SalesOrderSearchDTO>() { TotalCount = 0, TotalPage = 0, List = new List<SalesOrderSearchDTO>() };
            try
            {
                RefAsync<int> totaCount = 0;
                RefAsync<int> totalPage = 0;
                var list = _db.Queryable<SalesOrder, SalesOrderMaterial>((s, sm) => s.ItemBianma == sm.ItemBianma).Select((s, sm) => new SalesOrderSearchDTO()
                {

                    SalesOrderId = s.SalesOrderId,
                    DocumentNumber = s.DocumentNumber,
                    DocumentDate = s.DocumentDate,
                    DocumentStatus = s.DocumentStatus,
                    DocumentType = s.DocumentType,
                    BusinessType = s.BusinessType,
                    BusinessStatus = s.BusinessStatus,
                    SalesDepartmentName = s.SalesDepartmentName,
                    SalesStaff = s.SalesStaff,
                    OperatorName = s.OperatorName,
                    SalesType = s.SalesType,
                    ModeDelivery = s.ModeDelivery,
                    CustomerProfileName = s.CustomerProfileName,
                    ContractNumber = s.ContractNumber,
                    PaymentTerms = s.PaymentTerms,
                    DeliverDate = s.DeliverDate,
                    DeliveryStatus = s.DeliveryStatus,
                    Consignee = s.Consignee,
                    Phone = s.Phone,
                    Address = s.Address,
                    DestinationCountry = s.DestinationCountry,
                    NoteInformation = s.NoteInformation,
                    ItemBianma = s.ItemBianma,
                    SalesOrderMaterialId = sm.SalesOrderMaterialId,
                    MaterialName = sm.MaterialName,
                    TypeSpecification = sm.TypeSpecification,
                    Color = sm.Color,
                    Quantity = sm.Quantity,
                    UnitPrice = sm.UnitPrice,
                    Amount = sm.Amount,
                    Numberofpackages = sm.Numberofpackages,
                    Pattern = sm.Pattern,
                    Quality = sm.Quality,
                    Packing = sm.Packing,
                    Remark = sm.Remark,
                });
                if (!string.IsNullOrEmpty(request.DocumentNumber)) //单据编码
                {
                    list = list.Where(s => s.DocumentNumber == request.DocumentNumber);
                }
                if (!string.IsNullOrEmpty(request.CustomerProfileName))//客户名称
                {
                    list = list.Where(s => s.CustomerProfileName == request.CustomerProfileName);
                }
                if (!string.IsNullOrEmpty(request.MaterialName))//物料名称
                {
                    list = list.Where(s => s.MaterialName.Contains(request.MaterialName));
                }
                if (!string.IsNullOrEmpty(request.SalesStaff))//销售人员
                {
                    list = list.Where(s => s.SalesStaff.Contains(request.SalesStaff));
                }
                if (!string.IsNullOrEmpty(request.SalesType))//销售类型 
                {
                    list = list.Where(s => s.SalesType == request.SalesType);
                }
                var res = await list.ToPageListAsync(request.PageIndex, request.PageSize, totaCount, totalPage);
                page.TotalCount = totaCount;
                page.TotalPage = totalPage;
                page.List = res;
                if (page.List.Any())
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = page;
                    result.Msg = "获取当前条件下销售订单信息成功！";
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return result;
        }
    }
}
